package com.anlu.rabbitmq.setmsg;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ReplyToProducer {
    public final static String EXCHANGE_NAME = "replyto";
    public static void main(String[] args)  throws IOException, TimeoutException {

        /* 创建连接,连接到RabbitMQ*/
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        Connection connection = connectionFactory.newConnection();

             /*创建信道*/
       final Channel channel = connection.createChannel();
        /*创建持久化交换器*/
        channel.exchangeDeclare(EXCHANGE_NAME,"direct",false);

        /**
         * 声明一个队列
         */
        String queueName = "replyto";
        channel.queueDeclare(queueName,false,false,
                false,null);
        /**
         * 绑定，将队列和交换器通过路由键进行绑定
         */
        String routeKye = "error";
        channel.queueBind(queueName,ReplyToProducer.EXCHANGE_NAME,routeKye);
        System.out.println("waiting for message........");

           /*声明了一个消费者*/
        final Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("Received["+envelope.getRoutingKey()
                        +"]"+message);
                AMQP.BasicProperties respProp
                        = new AMQP.BasicProperties.Builder()
                        .replyTo(properties.getReplyTo())
                        .correlationId(properties.getMessageId())
                        .build();

                channel.basicPublish("", respProp.getReplyTo() ,
                        respProp ,
                        ("Hi,"+message).getBytes("UTF-8"));
            }
        };
        /*消费者正式开始在指定队列上消费消息*/
        channel.basicConsume(queueName,true,consumer);

    }
}
